package com.ldc.framework.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonlibs.conf.RouteConf
import com.ldc.commonlibs.listener.OnRowListener
import com.ldc.commonlibs.uts.ApiUtils
import com.ldc.commonlibs.uts.MessageUts
import com.ldc.commonlibs.uts.ViewModelUtils
import com.ldc.commonres.common.VBMFragment
import com.ldc.commonres.views.StateViewLayout
import com.ldc.framework.R
import com.ldc.framework.activity.CoInActivity
import com.ldc.framework.activity.CollectArticleListActivity
import com.ldc.framework.activity.RankActivity
import com.ldc.framework.activity.SearchActivity
import com.ldc.framework.adapter.ProfileitemListAdapter
import com.ldc.framework.databinding.FrameworkFragmentProfileBinding
import com.ldc.framework.model.ProfileViewItemModel
import com.ldc.framework.viewmodel.FrameworkViewModelBase


class ProfileFragment : VBMFragment<FrameworkFragmentProfileBinding, FrameworkViewModelBase>() {
    private var isLogin: Boolean = false
    private var profiledListAdapter: ProfileitemListAdapter? = null

    companion object {
        private const val REFRESH_CODE = 0x123
        private const val ARG_USER_ID: String = "ARG_USER_ID"
        fun newInstance(userId: String = ""): ProfileFragment = ProfileFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_USER_ID, userId)
            }
        }
    }

    override fun processMessage(msg: Message): Boolean {
        when (msg.what) {
            REFRESH_CODE -> {
                getUserInfo()
            }
        }

        return super.processMessage(msg)
    }

    override fun initStateViewLayout(): StateViewLayout? =
        StateViewLayout.init(this, R.id.refresh_view)

    override fun main() {
        addOnReTryListener(object : OnRowListener<Int> {
            override fun onRow(v: View, data: Int) {
                MessageUts.sendMessage(getHandler(), REFRESH_CODE)
            }
        })
        initAdapter()
        // 主线程执行

        MessageUts.sendMessage(getHandler(), REFRESH_CODE)
        viewBind?.let { vb ->
            // 下拉刷新
            vb.refreshView.let { rv ->
                rv.setEnableLoadMore(false)
                rv.setOnRefreshListener {
                    //
                    MessageUts.sendMessage(getHandler(), REFRESH_CODE)
                }
            }
            vb.flLogin.setOnClickListener {
                ARouter.getInstance()
                    .build(RouteConf.LoginRoute.startEnter)
                    .navigation(requireContext(), object : NavigationCallback {
                        override fun onFound(postcard: Postcard?) {
                            requireActivity().finish()
                        }

                        override fun onLost(postcard: Postcard?) {

                        }

                        override fun onArrival(postcard: Postcard?) {

                        }

                        override fun onInterrupt(postcard: Postcard?) {

                        }
                    })
            }
        }


    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FrameworkFragmentProfileBinding =
        FrameworkFragmentProfileBinding.inflate(inflater, container, false)

    override fun createViewModel(): FrameworkViewModelBase =
        ViewModelUtils.create(this, FrameworkViewModelBase::class.java)


    // 获取用户信息
    @SuppressLint("SetTextI18n")
    private fun getUserInfo() {
        showLoadingView()
        viewModel?.userInfo()?.observe(this) {
            showContentView()
            viewBind?.refreshView?.also { rv ->
                if (rv.state.isOpening) {
                    rv.finishRefresh()
                }
            }

            isLogin = ApiUtils.isLogin(it)
            //
            if (ApiUtils.isSuccess(it)) {
                if (isLogin) {
                    viewBind?.flLogin?.visibility = View.GONE
                }
                // 判断是否登录
                viewBind?.tvUserId?.text = "用户ID：${it.data?.userInfo?.id}"
                viewBind?.tvUserName?.text = "用户名：${it.data?.userInfo?.username}"
                viewBind?.tvUserCoinCount?.text = "金币：${it.data?.coinInfo?.coinCount}"
                viewBind?.tvUserLevel?.text = "等级：${it.data?.coinInfo?.level}"
                viewBind?.tvUserRank?.text = "排名：${it.data?.coinInfo?.rank}"
                viewBind?.ivIcon?.setImageResource(com.ldc.commonres.R.drawable.res_icon_user_icon)
            } else {
                showEmptyView()
                viewBind?.flLogin?.visibility = View.VISIBLE
            }
        }
    }


    private fun initAdapter() {
        val itemList = arrayListOf<ProfileViewItemModel>(
            ProfileViewItemModel("排行榜", 1, com.ldc.commonres.R.drawable.res_icon_rank),
            ProfileViewItemModel("签到", 2, com.ldc.commonres.R.drawable.res_icon_coin),
            ProfileViewItemModel("收藏", 3, com.ldc.commonres.R.drawable.res_icon_my_collect),
            ProfileViewItemModel("消息", 4, com.ldc.commonres.R.drawable.res_icon_message),
            ProfileViewItemModel("隐私", 5, com.ldc.commonres.R.drawable.res_icon_privacy),
            ProfileViewItemModel("关于", 6, com.ldc.commonres.R.drawable.res_icon_about),
            ProfileViewItemModel("搜索", 7, com.ldc.commonres.R.drawable.res_icon_action_search),
            ProfileViewItemModel("Compose测试", 8, com.ldc.commonres.R.drawable.res_icon_about),
        )
        profiledListAdapter = ProfileitemListAdapter().apply {
            addOnRowListener(object : OnRowListener<ProfileViewItemModel> {
                override fun onRow(v: View, data: ProfileViewItemModel) {
                    // 点击事件
                    when (data.code) {
                        1 -> {
                            RankActivity.start(this@ProfileFragment, data.name)
                        }
                        2 -> {
                            CoInActivity.start(requireContext(), data.name)
                        }
                        3 -> {
                            CollectArticleListActivity.start(requireContext(), data.name)
                        }
                        4 -> {
                            ARouter.getInstance()
                                .build(RouteConf.MessageRoute.startEnter)
                                .navigation()
                        }
                        5 -> {
                            ARouter.getInstance()
                                .build(RouteConf.AboutRoute.privacyActivity)
                                .navigation()
                        }
                        6 -> {
                            ARouter.getInstance()
                                .build(RouteConf.AboutRoute.startEnter)
                                .navigation()
                        }
                        7 -> {
                            SearchActivity.start(requireContext(), "")
                        }
                        8 -> {
                            ARouter.getInstance()
                                .build(RouteConf.ComposeRoute.startEnter)
                                .navigation()
                        }
                    }
                }
            })
            newData(itemList)
        }
        viewBind?.let { vb ->
            vb.itemList.adapter = profiledListAdapter
            vb.itemList.setHasFixedSize(true)
            vb.itemList.layoutManager =
                GridLayoutManager(requireContext(), 3)
        }
    }


}